package com.zhss.dfs.datanode.server;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * 负责跟一组NameNode进行通信的offerService组件
 */
public class NameNodeOfferService {
    /**
     * 负责跟NameNode主节点通信的serviceActor的组件
     */
    private NameNodeServiceActor activeServiceActor;
    /**
     * 负责跟NameNode备节点通信的serviceActor的组件
     */
    private NameNodeServiceActor standByServiceActor;
    /**
     * dataNode上保存的serviceActor列表
     */
    private CopyOnWriteArrayList<NameNodeServiceActor> serviceActors;

    /**
     * 构造函数
     */
    public NameNodeOfferService(){
        this.activeServiceActor = new NameNodeServiceActor();
        this.standByServiceActor = new NameNodeServiceActor();

        serviceActors = new CopyOnWriteArrayList<NameNodeServiceActor>();
        this.serviceActors.add(activeServiceActor);
        this.serviceActors.add(standByServiceActor);
    }

    /**
     * 启动offerService组件
     */
    public void start(){
        //直接使用两个组件分别进行向主备两个NameNode节点进行注册
        register();
    }

    /**
     * 向主备两个NameNode节点进行注册
     */
    private void register(){
        try{
            CountDownLatch latch = new CountDownLatch(2);
            this.activeServiceActor.register(latch);
            this.standByServiceActor.register(latch);
            latch.await();
            System.out.println("主备NameNode全部注册完毕。。。。。。");
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 关闭指定的serviceActor
     * @param nameNodeServiceActor
     */
    public void shutdown(NameNodeServiceActor nameNodeServiceActor){
        this.serviceActors.remove(nameNodeServiceActor);
    }

    /**
     * 迭代遍历serviceActor
     */
    public void iterateServiceActors(){
        Iterator<NameNodeServiceActor> iterator = serviceActors.iterator();
        while (iterator.hasNext()){
            iterator.next();
        }
    }
}
